package com.xiaomi.servlet;

import com.xiaomi.entity.Cart;
import com.xiaomi.entity.User;
import com.xiaomi.service.CartService;
import com.xiaomi.service.impl.CartServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * TODO
 *
 * @author jy
 * @date 2021/5/24
 */
@WebServlet("/cart")
public class CartServlet extends BaseServlet {

    private final CartService cartService = new CartServiceImpl();

    /**
     * 将商品添加购物车
     */
    protected String createCart(HttpServletRequest req, HttpServletResponse resp) {
        User user = (User) req.getSession().getAttribute("loginUser");
        if (user == null) {
            return "redirect:/login.jsp";
        }
        String pid = req.getParameter("pid");
        int count = cartService.createCart(pid, user.getUid());
        if (count > 0) {
            return "forward:/cartSuccess.jsp";
        }
        req.setAttribute("msg", "添加购物车失败");
        return "forward:/message.jsp";
    }

    /**
     * 查询购物车信息
     */
    protected String showCartsByUid(HttpServletRequest req, HttpServletResponse resp) {
        User user = (User) req.getSession().getAttribute("loginUser");
        if (user == null) {
            return "redirect:/login.jsp";
        }
        List<Cart> carts = cartService.showCartsByUid(user.getUid());
        req.setAttribute("carts", carts);
        return "forward:/cart.jsp";
    }

    /**
     * 对更新购物车数量时,更新数据库中购物车的数量与价格
     */
    protected String update(HttpServletRequest req, HttpServletResponse resp) {
        String cid = req.getParameter("cid");
        String price = req.getParameter("price");
        String num = req.getParameter("num");
        int count = cartService.update(cid, num, price);
        if (count > 0) {
            return "forward:/cart?method=showCartsByUid";
        }
        req.setAttribute("msg", "购物车数量修改失败");
        return "forward:/message.jsp";
    }

    /**
     * 通过cid删除购物车单条信息
     */
    protected String delete(HttpServletRequest req, HttpServletResponse resp) {
        String cid = req.getParameter("cid");
        int count = cartService.delete(cid);
        if (count > 0) {
            return "forward:/cart?method=showCartsByUid";
        }
        req.setAttribute("msg", "删除购物车记录失败");
        return "forward:/message.jsp";
    }

    /**
     * 清空购物车
     */
    protected String clear(HttpServletRequest req, HttpServletResponse resp) {
        String uid = req.getParameter("uid");
        int count = cartService.clear(uid);
        if (count > 0) {
            return "forward:/cart?method=showCartsByUid";
        }
        req.setAttribute("msg", "清空购物车失败");
        return "forward:/message.jsp";
    }
}
